﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Security;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Windows.Forms;


namespace MotesRummet_JQueryWebPart.VisualWebPart1
{
    [ToolboxItem(false)]
    public partial class VisualWebPart1 : System.Web.UI.WebControls.WebParts.WebPart
    {
        string SiteURL;
        string SiteTitle;
        string SiteDescription;

        protected override void OnInit(EventArgs e)
        {
            
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
           
            
            if (!Page.IsPostBack)
            {
                PopulateDropdowns();
                

            }
            else
            {
                
            }
        }

        //protected override void OnPreRender(EventArgs args)
        //{
        //    if (this.Page.IsPostBack)
        //    {
        //        UpdateNavCreate();
        //    }
        //}



        /// <summary>
        /// Button: Create sub-site
        /// </summary>
        protected void btn_createSite_Click1(object sender, EventArgs e)
        {

            SPWeb web = SPContext.Current.Site.RootWeb;

            try
            {
                web.AllowUnsafeUpdates = true;


                SiteURL = hdnSiteUrl.Value;
                SiteTitle = hdnSiteTitle.Value;
                SiteDescription = hdnSiteDescription.Value;

                SPWebTemplate template = web.GetAvailableWebTemplates((uint)1033)
                                                                       .Cast<SPWebTemplate>()
                                                                       .Where(x => x.Title.Equals("MR_WebSite_Template"))
                                                                       .First();

                using (SPWeb myWeb = SPContext.Current.Site.OpenWeb(SiteURL))
                {
                    if (!String.IsNullOrEmpty(SiteURL) && !String.IsNullOrEmpty(SiteTitle) && !myWeb.Exists)
                    {
                        SPWeb newWeb = web.Site.AllWebs.Add(SiteURL, SiteTitle, SiteDescription, 1033, template, true, false);
                        newWeb.Update();
                        txtBox_Url.Text = string.Empty;
                        txtBox_Title.Text = string.Empty;
                        txt_description.Text = string.Empty;
                        lbl_update.BackColor = System.Drawing.Color.Green;
                        lbl_update.ForeColor = System.Drawing.Color.White;
                        lbl_update.Font.Size = 10;
                        lbl_update.Text = "Success: " + SiteTitle + " har skapats";
                        
                        createNav();
                        AddWebToDeleteSitesDropdown(newWeb.Title, newWeb.ID);
                    }
                    else if (String.IsNullOrEmpty(SiteURL) || String.IsNullOrEmpty(SiteTitle))
                    {
                        lbl_update.BackColor = System.Drawing.Color.Red;
                        lbl_update.ForeColor = System.Drawing.Color.White;
                        lbl_update.Font.Size = 15;
                        lbl_update.Text = "Sidan måste ha ett URL-namn och en Titel";
                    }
                    else
                    {
                        lbl_update.BackColor = System.Drawing.Color.Red;
                        lbl_update.ForeColor = System.Drawing.Color.White;
                        lbl_update.Font.Size = 15;
                        lbl_update.Text = "Siten finns redan";
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }

        /// <summary>
        /// Button: Delete sub-site
        /// </summary>
        protected void btn_delete_web_Click(object sender, EventArgs e)
        {
            SPSite site = SPContext.Current.Site;

            using (SPWeb web = site.OpenWeb())
            {
                SPWebCollection webColl = web.GetSubwebsForCurrentUser();

                string selVal = DropDwn_Delete_Web.SelectedValue;

                var result = (from w in webColl
                              where w.Title.Equals(selVal)
                              select w).FirstOrDefault();

                try
                {
                    lbl_delete.Text = "Success: Sidan: <b>" + result.Title + "</b> togs bort.";
                    //Ta bort från dropdown

                    DropDwn_Delete_Web.Items.Remove(result.Title);
                    //ta bort sidan (från collection)
                    result.Delete();
                    
                }

                catch (Exception)
                {
                    lbl_delete.Text = "Error: Sidan finns inte?";
                }

            }
            //PopulateDropdowns();
        }


        /// <summary>
        /// Add new site to DropDownList...
        /// </summary>
        private void AddWebToDeleteSitesDropdown(string title, Guid guid)
        {
            DropDwn_Delete_Web.Items.Add(new ListItem(title, guid.ToString()));
        }


        /// <summary>
        /// Populates dropdown with...
        /// </summary>
        private void PopulateDropdowns()
        {
            //SiteCollection som vi befinner oss i
            SPSite site = SPContext.Current.Site;
            
                //Web som finns i ovanstående SiteColl
                using (SPWeb web = site.OpenWeb())
                {
                    //Ta fram alla subsites för current user (inte top-site)
                    SPWebCollection sub = web.GetSubwebsForCurrentUser();
                    //Loopa igenom subKollektionen och lägg till i dropdownlistan.
                    foreach (SPWeb subsites in sub)
                    {
                        DropDwn_Delete_Web.Items.Add(subsites.Title);
                        subsites.Dispose();
                    }
                }
        }

        public void UpdateNavCreate()
        {
            SPSite site = SPContext.Current.Site;
            
                //Web som finns i ovanstående SiteColl
            using (SPWeb web = site.OpenWeb())
            {
                SPNavigationNodeCollection node = web.Navigation.TopNavigationBar;
                foreach (SPNavigationNode nav in node)
                {
                    if ("Hej" == nav.Title)
                    {
                        nav.Update();
                        Console.WriteLine(nav.Title);
                    }
                }
            }
        }

            //SPSite site = SPContext.Current.Site;
            //SPWebCollection webs = site.AllWebs;
            ////SiteTitle = txtBox_Title.Text;
            //foreach (SPWeb web in webs)
            //{
            //    SPNavigationNodeCollection node = web.Navigation.TopNavigationBar;
                
            //    foreach (SPNavigationNode navs in node)
            //    {
            //        if ("Hej" == navs.Title)
            //        {
            //            Console.WriteLine(navs.Title);
            //            SPNavigationNode navv = new SPNavigationNode(navs.Title, web.ServerRelativeUrl);

            //        }
            //    }
            //}
        //}



        /// <summary>
        /// Creates new navigation for sub-site...
        /// </summary>
        public void createNav()
        {
            //using (SPSite site = new SPSite("http://motesrummet.se"))
            SPSite site = SPContext.Current.Site;
            {
                using (SPWeb webb = site.OpenWeb(SiteURL))
                
                {
                    if (!webb.IsRootWeb)
                        webb.Navigation.UseShared = true;

                    if (!webb.ParentWeb.Navigation.UseShared)
                    {
                        SPNavigationNodeCollection topnav = webb.ParentWeb.Navigation.TopNavigationBar;
                        SPNavigationNode node = topnav
                            .Cast<SPNavigationNode>()
                            .FirstOrDefault(n => n.Url.Equals(webb.ServerRelativeUrl));

                        if (node == null)
                        {
                            string LinkTitle = SiteTitle;

                            if (LinkTitle.Length > 15)
                            {
                                LinkTitle = LinkTitle.Substring(0, 12) + "...";

                                node = new SPNavigationNode(LinkTitle, webb.ServerRelativeUrl);
                                node = topnav.AddAsLast(node);
                            }
                            else
                            {
                                node = new SPNavigationNode(LinkTitle, webb.ServerRelativeUrl);
                                node = topnav.AddAsLast(node);
                            }
                            node.Update();
                            
                        }
                    }
                }
            }
        }

        protected void txtBox_Title_TextChanged(object sender, EventArgs e)
        {

        }


    }
}
